package com.voto.sunflower.activity.me;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.voto.sunflower.R;
import com.voto.sunflower.SunflowerApplication;
import com.voto.sunflower.activity.BaseActivity;
import com.voto.sunflower.activity.me.UpdateAvatarCallback.UpdateAvatarListener;
import com.voto.sunflower.activity.me.UpdateMeCallback.UpdateMeListener;
import com.voto.sunflower.dao.User;
import com.voto.sunflower.model.request.UpdateMe;
import com.voto.sunflower.model.response.UpdateAvatarResponse;
import com.voto.sunflower.model.response.UserResponse;
import com.voto.sunflower.retrofit.ClientHttpService;
import com.voto.sunflower.retrofit.RestError;
import com.voto.sunflower.utils.ExUtils;
import com.voto.sunflower.utils.ImageUtils;
import com.voto.sunflower.utils.URLHelper;
import com.voto.sunflower.utils.Utils;
import com.voto.sunflower.widget.BottomDialog;
import com.voto.sunflower.widget.BottomDialog.OnClickDialogListener;

public class PersonalSettingActivity extends BaseActivity implements
		OnClickListener {


	protected String mGender;
	protected String mBirthday;
	private TextView birthdayTextView;
	private TextView nameTextView;
	private User mUser;
	private TextView genderTextView;
	private RelativeLayout avatarLayout;
	private ImageView avatarImageView;
	
	private String AVATAR_TEMP_PATH = SunflowerApplication.AVATAR_TEMP_PATH
			+SunflowerApplication.getmUser().getId()
			+SunflowerApplication.AVATAR_NAME;
	// 请求码
	private final int REQUEST_CODE_PICK_IMAGE = 0;
	protected final int REQUEST_CODE_PHOTO_GRAPH = 1;
	private final int REQUEST_CODE_PHOTO_RESOULT = 2;
	// 标志
	private final static String TAG = "PersonalSettingActivity";
	private final String IMAGE_UNSPECIFIED = "image/*";
	private TextView phoneTextView;
	private UpdateAvatarCallback mUpdateAvatarCallback;
	private Uri photoUri;
	private UpdateMeCallback mUpdateMeCallback;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "PersonalSettingActivity onCreate-------->");
		setContentView(R.layout.activity_me_personal_info_detail);
		
		setCallback();
		initComponent();
		initView();
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG, "PersonalSettingActivity onResume-------->");
		setUserInfo();
	}
	
	
	/**
	 * 设置http接口回调函数
	 */
	private void setCallback() {
		mUpdateAvatarCallback = new UpdateAvatarCallback();
		mUpdateAvatarCallback.setListener(new UpdateAvatarListener() {

			@Override
			public void success(UpdateAvatarResponse updateAvatarResponse,
					Response response) {
				Log.d(TAG, "update avatar success------>");
				String avatar_uri = updateAvatarResponse.getImage_url();
				// 更新本地
				mUser.setAvatar_url(avatar_uri);
				SunflowerApplication.setmUser(mUser);
				// 更新服务器
				UpdateMe update = new UpdateMe();
				update.setAvatar_url(avatar_uri);
				ClientHttpService.getMeService().updateMe(update,mUpdateMeCallback);
			}

			@Override
			public void failure(RetrofitError error) {
				Log.d(TAG, "update avatar fail------>");
				dismissDialog();
				if (error.getResponse() != null) {
					int statusCode = error.getResponse().getStatus();
					if (statusCode == 500 || statusCode == 501) {
						final RestError body = (RestError) error.getBodyAs(RestError.class);
						showNetworkErrorDialog(body.errorDetails, null);
					} else if (statusCode == 408) {
						showNetworkErrorDialog(getString(R.string.connect_overtime), null);
					} else {
						showNetworkErrorDialog(error.getMessage(), null);
					}
				}
			}
		});
		mUpdateMeCallback = new UpdateMeCallback();
		mUpdateMeCallback.setListener(new UpdateMeListener() {
			
			@Override
			public void sucess(UserResponse arg0, Response arg1) {
				Log.d(TAG, "update Me sucess------>");
				dismissDialog();
				SunflowerApplication.setmUser(arg0.getUser());
			}
			
			@Override
			public void failure(RetrofitError error) {
				Log.d(TAG, "update Me fail------>");
				dismissDialog();
				if (error.getResponse() != null) {
					int statusCode = error.getResponse().getStatus();
					if (statusCode == 500 || statusCode == 501) {
						final RestError body = (RestError) error.getBodyAs(RestError.class);
						showNetworkErrorDialog(body.errorDetails, null);
					} else if (statusCode == 408) {
						showNetworkErrorDialog(getString(R.string.connect_overtime), null);
					} else {
						showNetworkErrorDialog(error.getMessage(), null);
					}
				}
			}
		});
	}

	private void initComponent() {
		// 设置键盘隐藏
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

		avatarImageView = (ImageView) findViewById(R.id.avatar_img_personal_detail);
		avatarLayout = (RelativeLayout) findViewById(R.id.personal_info_set_portrait);
		nameTextView = (TextView) findViewById(R.id.personal_info_name_str);
		birthdayTextView = (TextView) findViewById(R.id.personal_info_age_str);
		genderTextView = (TextView) findViewById(R.id.personal_info_gender_str);
		phoneTextView = (TextView) findViewById(R.id.personal_info_phone_str);

		findViewById(R.id.personal_info_set_portrait).setOnClickListener(this);
	}

	/**
	 * 从本地获取头像
	 */
	protected String getAvatarFromLocal() {
		SharedPreferences spf = getSharedPreferences("UserInfo", 0);
		return spf.getString("avatar_uri", "");
	}

	/**
	 * 初始化标题栏
	 */
	private void initView() {
		// 设置标题
		TextView actionBarTitle = (TextView) findViewById(R.id.title);
		actionBarTitle.setText(getString(R.string.me_personal_info));
		// 设置返回键
		TextView actionBarBack = (TextView) findViewById(R.id.back);
		actionBarBack.setText(getString(R.string.me_main_title));
		actionBarBack.setOnClickListener(this);
		// 设置存储键
		TextView actionBarOther = (TextView) findViewById(R.id.other);
		actionBarOther.setVisibility(View.INVISIBLE);
		actionBarOther.setText(getString(R.string.save_user_info));
		actionBarOther.setOnClickListener(null);
	}

	/**
	 * 更新用户信息
	 */
	private void updateUserInfo() {
		String name = nameTextView.getText().toString();
		// 更新数据
		updateLocal(name);
		updateServer(name);
	}

	private void updateServer(String name) {
		UpdateMe update = new UpdateMe();
		update.setName(name);
		update.setGender(mGender);
		update.setBirthday(mBirthday);
		ClientHttpService.getMeService().updateMe(update, mUpdateMeCallback);
	}

	private void updateLocal(String name) {
		mUser.setName(name);
		mUser.setGender(mGender);
		mUser.setBirthday(mBirthday);
		SunflowerApplication.setmUser(mUser);
	}

	/**
	 * 设置用户
	 */
	public void setUserInfo() {
		mUser = SunflowerApplication.getmUser();
		String name = mUser.getName();
		String phone = mUser.getPhone();
		String gender = mUser.getGender();
		String birthday = mUser.getBirthday();
		String avatar_uri = mUser.getAvatar_url();

		if (mUser != null) {
			nameTextView.setText(name);
			phoneTextView.setText(phone);
			if(birthday!=null){
				if(birthday.length()<=10){
					birthdayTextView.setText(birthday);
				}else{
					birthdayTextView.setText(mUser.getBirthday().substring(0, 10));
				}
			}
			setMyGender(gender);
			setMyAvatar(avatar_uri);
		}
	}

	private void setMyBirthday(String birthday) {
		String age = Utils.getAgetFromBirthday(birthday);
		birthdayTextView.setText(age);
	}

	private void setMyAvatar(String avatar_uri) {
		// 获取头像，有就缓存
		Bitmap bitmap = BitmapFactory
				.decodeFile(AVATAR_TEMP_PATH);
		if (bitmap != null) {
			avatarImageView.setImageBitmap(bitmap);
		} else {
			ExUtils.loadImage(URLHelper.getAbsoluteUrl(avatar_uri),
					R.drawable.unkown_person, avatarImageView);
		}
	}

	public void cacheAvatar(Bitmap bitmap) {
		  Log.e(TAG, "保存图片");
		  File f = new File(SunflowerApplication.AVATAR_TEMP_PATH,SunflowerApplication.getmUser().getId()+SunflowerApplication.AVATAR_NAME);
		  if (f.exists()) {
		   f.delete();
		  }
		  try {
		   FileOutputStream out = new FileOutputStream(f);
		   bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
		   out.flush();
		   out.close();
		   Log.i(TAG, "已经保存");
		  } catch (FileNotFoundException e) {
		   // TODO Auto-generated catch block
		   e.printStackTrace();
		  } catch (IOException e) {
		   // TODO Auto-generated catch block
		   e.printStackTrace();
		  }

		 }

	private void setMyGender(String gender) {
		genderTextView.setText(gender);
	}

	public void modifyPhone(View view) {
		startActivity(new Intent(this, ModifyPhoneActivity.class));
	}

	public void modifyPassword(View view) {
		startActivity(new Intent(this, ModifyPasswordActivity.class));
	}

	public void modifyName(View view) {
		Intent intent = new Intent(this, ModifyNameActivity.class);
		String name = nameTextView.getText().toString();
		intent.putExtra("userName", name);
		startActivity(intent);
	}
	
	public void modifyGender(View view){
		Intent intent = new Intent(this, ModifyGenderActivity.class);
		String gender = genderTextView.getText().toString();
		intent.putExtra("gender", gender);
		startActivity(intent);
	}
	
	public void modifyBirthday(View view){
		Intent intent = new Intent(this, ModifyBirthDayActivity.class);
		String birthday = birthdayTextView.getText().toString();
		intent.putExtra("birthday", birthday);
		startActivity(intent);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.personal_info_set_portrait:
			showPicSelectMode();
			break;
		case R.id.back:
			finish();
			break;
		default:
			break;
		}
	}

	private void showPicSelectMode() {
		BottomDialog dialog = new BottomDialog(this,
				R.style.MyDialogBottomNormal);
		dialog.setmTitle("个人信息");
		String str[] = new String[3];
		str[0] = "从相册选择";
		str[1] = "使用手机拍照";
		str[2] = "取消";
		dialog.setItemNames(str);
		dialog.setOnClickDialogListener(new OnClickDialogListener() {

			@Override
			public void onClick(int index) {
				switch (index) {
				case 0:// 从相片选择
					getImageFromAlbum();
					break;
				case 1:// 使用手机照相
					takePhoto();
					break;
				case 2:// 取消键
					break;
				default:
					break;
				}
			}
		});
		dialog.show();
	}

	/**
	 * 拍照获取图片
	 */
	private void takePhoto() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		ContentValues values = new ContentValues();
		photoUri = this.getContentResolver().insert(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
		startActivityForResult(intent, REQUEST_CODE_PHOTO_GRAPH);
	}

	/**
	 * 从相册获取图片
	 */
	protected void getImageFromAlbum() {
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("image/*");// 相片类型
		startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
			case REQUEST_CODE_PICK_IMAGE:
				Uri uri = data.getData();
				if (uri == null) {
					return;
				}
				handleAlbumPic(uri);
				break;
			case REQUEST_CODE_PHOTO_GRAPH:
				startPhotoZoom(photoUri);
				break;
			case REQUEST_CODE_PHOTO_RESOULT:
				handleCameraPic(data);
				break;
			default:
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void handleAlbumPic(Uri uri) {
		String img_path = getPicPathByUri(uri);
		String path = this.getCacheDir().getPath() + "/" + System.currentTimeMillis() + ".jpg";
		try {
			ImageUtils.resampleImageAndSaveToNewLocation(img_path, path);
		} catch (Exception e) {
			path = img_path;
			e.printStackTrace();
		}
		// 设置头像
		Bitmap bitmap = BitmapFactory.decodeFile(path);
		avatarImageView.setImageBitmap(bitmap);
		upLoadAvatar(path);
		cacheAvatar(bitmap);
	}

	private void upLoadAvatar(String path) {
		showBlankWaitDialog();
		File file = new File(path);
		ClientHttpService.getOtherService().updateImg(
				new TypedFile("image/jpeg", file), mUpdateAvatarCallback);
	}

	private String getPicPathByUri(Uri uri) {
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
		int actual_image_column_index = actualimagecursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		actualimagecursor.moveToFirst();
		return actualimagecursor.getString(actual_image_column_index);
	}

	/**
	 * 处理拍照的图片
	 */
	public void handleCameraPic(Intent data) {
		Uri uri = data.getData();
		if (uri == null) {
			Bundle extras = data.getExtras();
			if (extras != null) {
				Bitmap photo = extras.getParcelable("data");
				cacheAvatar(photo);
				upLoadAvatar(AVATAR_TEMP_PATH);
				avatarImageView.setImageBitmap(photo); // 把图片显示在ImageView控件上
			}
		} else {
			avatarImageView.setImageBitmap(ImageUtils.getBitmapFromUri(uri,
					this));
		}
	}

	/**
	 * 
	 * 收缩图片
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 300);
		intent.putExtra("outputY", 500);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, REQUEST_CODE_PHOTO_RESOULT);
	}
}
